﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using WebGioiThieu.Models;

namespace WebGioiThieu.Areas.Admin.Controllers
{
    public class AccountManagerController : Controller
    {
        //
        // GET: /Admin/AccountManager/

        private IntroductionWebDBEntities db = new IntroductionWebDBEntities();
        protected override void Initialize(System.Web.Routing.RequestContext requestContext)
        {
            base.Initialize(requestContext);
        }
        [CustomAuthorize]
        public ActionResult Index(string key, int? page)
        {
            int total, pageSize = 10;
            int pageNumber = (page ?? 1);
            IEnumerable<aspnet_Users> user;
            if (!string.IsNullOrEmpty(key))
            {
                var users = (from u in db.aspnet_Users
                             where u.UserName.Contains(key)
                             orderby u.UserName ascending
                             select u);
                user = users.Skip((pageNumber - 1) * pageSize).Take(pageSize).ToList();
                total = users.Count();
            }
            else
            {
                var users = (from u in db.aspnet_Users orderby u.UserName ascending select u);
                user = users.Skip((pageNumber - 1) * pageSize).Take(pageSize).ToList();
                total = users.Count();
            }
            var pages = new PageInfo { PageSize = pageSize, TotalItem = total, Url = "/Admin/AccountManager/Index", Current = pageNumber };
            ViewBag.Page = pages;
            return View(user);
        }
        [CustomAuthorize]
        public ActionResult Create()
        {
            ViewBag.Roles = db.aspnet_Roles.ToList();
            return View();
        }
        [CustomAuthorize]
        [HttpPost]
        public ActionResult Create(CreateModel model, FormCollection collection)
        {
            IEnumerable<string> roles = ToRoles(collection);
            if (ModelState.IsValid)
            {
                MembershipCreateStatus createStatus;
                Membership.CreateUser(model.UserName, model.Password, model.Email
                    , null, null, true, null, out createStatus);
                if (createStatus == MembershipCreateStatus.Success)
                {
                    //Roles.AddUserToRoles(model.UserName, roles.ToArray());
                    if (!model.Activated)
                    {
                        string key = Membership.GetUser(model.UserName).ProviderUserKey.ToString();
                    }
                    return RedirectToAction("Index", "AccountManager");
                }
                else
                {
                    return null;
                }
            }
            var roleObjects = db.aspnet_Roles.ToList();
            roleObjects.ForEach(r => r.IsSelect = roles.Contains(r.RoleName));
            ViewBag.Roles = roleObjects;
            return View(model);
        }
        public PartialViewResult Error()
        {
            return PartialView("Error", Url.Action("Index"));
        }
        private IEnumerable<string> ToRoles(FormCollection collection)
        {
            return (from string s in collection.AllKeys where s.StartsWith("[RoleId].") select s.Replace("[RoleId].", "")).ToList();
        }
        [CustomAuthorize]
        public ActionResult Delete(string id)
        {
            try
            {
                var user = db.aspnet_Users.SingleOrDefault(m => m.UserId.Equals(new Guid(id)));
                if (user == null)
                {
                    throw new ArgumentException("khong ton tai!", id);
                }
                return View(user);
            }
            catch (Exception)
            {
                return Error();
            }
        }
        [CustomAuthorize]
        [HttpPost]
        public ActionResult Delete(string id, FormCollection collection)
        {
            try
            {
                var user = db.aspnet_Users.SingleOrDefault(u => u.UserId.CompareTo(new Guid(id)) == 0);
                System.Web.Security.Membership.DeleteUser(user.UserName);
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
        [CustomAuthorize]
        public ActionResult Edit(string id)
        {
            try
            {
                var user = db.aspnet_Users.SingleOrDefault(m => m.UserId.Equals(new Guid(id)));
                if (user == null)
                {
                    throw new ArgumentException("khong ton tai!", id);
                }
                CreateModel model = new CreateModel()
                {
                    Activated = user.aspnet_Membership.IsApproved,
                    Email = user.aspnet_Membership.Email,
                    PasswordQuestion = user.aspnet_Membership.PasswordQuestion,
                    PasswordAnswer = user.aspnet_Membership.PasswordAnswer,
                    UserName = user.UserName
                };

                string[] roles = new string[0];
                try { roles = Roles.GetRolesForUser(user.UserName); }
                catch { }

                var roleObjects = db.aspnet_Roles.ToList();
                roleObjects.ForEach(r => r.IsSelect = roles.Contains(r.RoleName));
                ViewBag.Roles = roleObjects;
                return View(model);
            }
            catch
            {
                return Error();
            }
        }

        //
        // POST: /AccountManager/Edit/5
        [CustomAuthorize]
        [HttpPost]
        public ActionResult Edit(string id, CreateModel model, FormCollection collection)
        {
            try
            {
                IEnumerable<string> roleSelects = ToRoles(collection);
                bool changePassword = !string.IsNullOrEmpty(model.Password);
                if (!changePassword)
                {
                    model.Password = model.ConfirmPassword = "098516f9b30b431735a3ea5259858daf";
                    ModelState.SetModelValue("Password", new ValueProviderResult(model.Password, model.Password, null));
                    ModelState.SetModelValue("ConfirmPassword", new ValueProviderResult(model.ConfirmPassword, model.ConfirmPassword, null));
                    int index = ModelState.Keys.ToList().FindIndex(m => m == "Password");
                    ModelState.Values.ToList()[index].Errors.Clear();
                }
                // TODO: Add update logic here
                if (ModelState.IsValid)
                {

                    var user = System.Web.Security.Membership.GetUser(new Guid(id));
                    if (user == null)
                    {
                        throw new ArgumentException("khong ton tai", id);
                    }
                    user.IsApproved = model.Activated;
                    user.Email = model.Email;
                    System.Web.Security.Membership.UpdateUser(user);
                    if (changePassword)
                    {
                        bool changedrs = user.ChangePassword(user.ResetPassword(), model.Password);
                    }
                    var roleExists = new List<string>();
                    try { roleExists = Roles.GetRolesForUser(user.UserName).ToList(); }
                    catch { }
                    var roleSelectsAdd = roleSelects.ToList();
                    var roleSelectsDel = new List<string>();
                    roleExists.ForEach(m =>
                    {
                        if (roleSelectsAdd.Contains(m))
                        {
                            roleSelectsAdd.Remove(m);
                        }
                        else
                        {
                            roleSelectsDel.Add(m);
                        }
                    });



                    if (roleSelectsAdd.Count > 0)
                        Roles.AddUserToRoles(user.UserName, roleSelectsAdd.ToArray());
                    if (roleSelectsDel.Count > 0)
                        Roles.RemoveUserFromRoles(user.UserName, roleSelectsDel.ToArray());
                    return RedirectToAction("Index");
                }
                var roleObjects = db.aspnet_Roles.ToList();
                roleObjects.ForEach(r => r.IsSelect = roleSelects.Contains(r.RoleName));
                ViewBag.Roles = roleObjects;
                return View(model);
            }
            catch
            {
                return Error();
            }
        }
        [CustomAuthorize]
        public ActionResult Details(string id)
        {
            aspnet_Users user = new aspnet_Users();
            if (!string.IsNullOrEmpty(id))
                user = db.aspnet_Users.Single(u => u.UserId.CompareTo(new Guid(id)) == 0);
            else
                if (!string.IsNullOrEmpty(User.Identity.Name))
                    user = db.aspnet_Users.Single(u => u.UserName.CompareTo(User.Identity.Name) == 0);
            return View(user);
        }

    }
}
